<?php

/*
 * Yollanan bütün değerler basit bir güvenlik kapısından geçiyor.
 * Sql injection için. 
 *  
 */
	error_reporting(E_ALL);
	
	$action		= $_GET["action"];
	
	$connection = mysql_connect("localhost","root","1970203022") or die("bağlanamadı");
	$db = mysql_select_db("yuichat",$connection);
	
	if( $action == "connect"){

		$sexPrefer 	= $_GET["sexPrefer"];		
		$urid = md5(uniqid(mt_rand(), true));
				
		switch($sexPrefer){			
			//doesn't matter
			case "0" : 	$sql = "SELECT * FROM channels WHERE sessionId2 IS NULL AND status=0 AND TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10";						
						$sex=0; $prefer=0; 
						break;
						 
			//man looking woman 
			case "1" : 	$sql = "SELECT * FROM channels WHERE sessionId2 IS NULL AND sex1=2 AND sexPrefer1=1 AND status=0 AND TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10";
						$sex=1; $prefer=2; 
						break;
						
			//woman looking man
			case "2" : 	$sql = "SELECT * FROM channels WHERE sessionId2 IS NULL AND sex1=1 AND sexPrefer1=2 AND status=0 AND TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10"; 
						$sex=2; $prefer=1; 
						break;
						
			//man looking man
			case "3" : 	$sql = "SELECT * FROM channels WHERE sessionId2 IS NULL AND sex1=1 AND sexPrefer1=1 AND status=0 AND TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10"; 
						$sex=1; $prefer=1; 
						break;
						
			//woman looking woman
			case "4" : 	$sql = "SELECT * FROM channels WHERE sessionId2 IS NULL AND sex1=2 AND sexPrefer1=2 AND status=0 AND TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10"; 
						$sex=2; $prefer=2; 
						break;
			
			//doesn't matter
			default  :	$sql = "SELECT * FROM channels WHERE sessionId2 IS NULL AND status=0 AND TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10"; 
						$sex=0; $prefer=0; 
						break; 
		}
			
		$rows = mysql_query($sql);
		$rowCount = mysql_num_rows($rows);		
		
		if($rowCount != 0){	
			
			/* varolan kanala abone olarak client ol */
			
			$sql = "SELECT * FROM channels WHERE (id >= RAND() * (SELECT MAX(id) FROM channels)) AND sessionId2 IS NULL AND status=0 AND TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10 LIMIT 1";
			$resultset = mysql_query($sql);
			$resultArray = mysql_fetch_array($resultset);

			$channelId = $resultArray["id"];			
			$me = $urid;
			$stranger = $resultArray["sessionId1"];		

			$currentTime = date("Y-m-d H:i:s", time());
			
			$sql = "UPDATE channels SET sessionId2='".$me."' , status=1, sex2=".$sex.", sexPrefer2=".$prefer.", lastConnected2='".$currentTime."' WHERE id=".$channelId;
			
			if(mysql_query($sql)){
				
				$jsonArray =  array(	
						"msg" => "connected",
						"me" => $me,
						"stranger" => $stranger,
						"channelId" => $channelId,					
						"timestamp" => $currentTime				
				);
				
				echo json_encode($jsonArray);
				
			}else{
				
				$jsonArray =  array(	
						"msg" => "connectionFAILED",
						"sql" => $sql,			
				);
				
				echo json_encode($jsonArray);
								
			}
			
															
		}else{
			
			/*Yeni kanal yaratılıyor ve host olunuyor*/
			
			$me = $urid;		
			$currentTime = date("Y-m-d H:i:s", time());	// bazen 5 saat ilerisini kaydediyor. Bu yüzden kontroller çalışmıyor.							
			$sql = "INSERT INTO channels(sessionId1,sex1,sexPrefer1,lastConnected1,status) VALUES('".$me."',".$sex.",".$prefer.",'".$currentTime."',0)";
									
			if(mysql_query($sql)){
				
				$channelId = mysql_insert_id();
								
				$jsonArray =  array(	
						"msg" => "connectionWAITING",
						"me" => $me,
						"channelId" => $channelId,						
						"timestamp" => $currentTime				
				);
				
				echo json_encode($jsonArray);
				
			}else{

				$jsonArray =  array(	
						"msg" => "connectionFAILED"			
				);
				
				echo json_encode($jsonArray);				
			}			
		}	
		
	}else if($action == "checkChannel"){
		
		$channelId 	= $_GET["channelId"];	
		$me			= $_GET["me"];
					
		$sql = "SELECT * FROM channels WHERE sessionId2 IS NOT NULL AND status=1 AND id=".$channelId;
		$resultset = mysql_query($sql);
		
		if(mysql_num_rows($resultset) != 0){
			
			$resultArray = mysql_fetch_array($resultset);		
			$me = $resultArray["sessionId1"];		
			$stranger = $resultArray["sessionId2"];
		
			$jsonArray =  array(	
					"msg" => "connected",
					"me" => $me,
					"stranger" => $stranger,
					"channelId" => $channelId,					
					"timestamp" => date("Y-m-d H:i:s", time())		
			);
			
			echo json_encode($jsonArray);
			
		}else{
			
			$jsonArray =  array(	
					"msg" => "connectionWAITING",
					"me" => $me,
					"channelId" => $channelId		
			);
			
			echo json_encode($jsonArray);
			
		}
		
	}else if($action == "write"){
		
		$channelId = $_GET["channelId"];
		$message = $_GET["message"];
		$me = $_GET["me"];
		$stranger = $_GET["stranger"];  
		
		$currentTime = date("Y-m-d H:i:s", time());
		
		$sql="INSERT INTO messages(channelId, message, messageFrom, messageTo, createdTime) VALUES($channelId,'$message','$me','$stranger','".$currentTime."')";
		mysql_query($sql);
		
		$jsonArray =  array(	
				"msg" => "writeOK",					
				"timestamp" => $currentTime				
		);
		
		echo json_encode($jsonArray);
			
		
	}else if($action == "read"){
		
		$channelId = $_GET["channelId"];
		$timestamp = $_GET["timestamp"];
		
		$sql = "SELECT * FROM messages WHERE createdTime > '$timestamp' AND channelId=$channelId";
				
		$resultset = mysql_query($sql);
		
		if(mysql_num_rows($resultset) > 0){
			
			while($resultArray = mysql_fetch_array($resultset)){
			
				$createdTime = $resultArray["createdTime"];
				
				$tmpArray[] =  array(	
						"message" => $resultArray["message"],
						"messageFrom" => $resultArray["messageFrom"],	
						"messageTo" => $resultArray["messageTo"],								
						"createdTime" => $resultArray["createdTime"]				
				);							
			}
			
			$_split_datehour = explode(' ',$createdTime);
       		$_split_data = explode("-", $_split_datehour[0]);
        	$_split_hour = explode(":", $_split_datehour[1]);
						
			$jsonArray =  array(	
					"msg" => "read",
					"messages" => $tmpArray,
					"timestamp" => $createdTime				
			);
			
			echo json_encode($jsonArray);			
			
		}else{
			$jsonArray =  array(	
				"msg" => "noMessage",				
				"timestamp" => date("Y-m-d H:i:s", time())				
			);
		
			echo json_encode($jsonArray);			
		}
		
		
	}else if($action == "heartBeat"){
		
		$channelId = $_GET["channelId"];
		$me = $_GET["me"];
		
		$sql = "SELECT * FROM channels WHERE id=$channelId AND status=2";
		$resultset = mysql_query($sql);
		
		if(mysql_num_rows($resultset) > 0){
			
			// karşı taraf disconnect olmuş
			
			$jsonArray =  array(	
					"msg" => "strangerIsDisconnected",
					"p"	=> "1"				
			);
			
			echo json_encode($jsonArray);
						
		}else{
					
			// karşı taraf hala bağlı
			
			// 1. kişi miyiz 2. kişi mi diye bakıyoruz						
			$sql = "SELECT * FROM channels WHERE id=$channelId AND sessionId2='$me'";			
			$resultset = mysql_query($sql);
		
			if(mysql_num_rows($resultset) > 0){
				//ben ikinci bağlanan kişiyim
				$sql = "SELECT TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10  FROM channels WHERE id=$channelId";
				$resultset = mysql_query($sql);
				$row = mysql_fetch_row($resultset);
				
				if($row[0] == 1){
					
					// Birinci hala sisteme bağlı ve bende son bağlantı zamanımı güncelliyorum				
					$sql = "UPDATE channels SET lastConnected2=NOW() WHERE id=$channelId";			
					mysql_query($sql);
					$jsonArray =  array(	
							"msg" => "heartBeat"						
					);
					
					echo json_encode($jsonArray);					
					
				}else{
					// Birinci 10 sn'den daha fazla süredir işlem yapmıyor. Yani disconnect
					$jsonArray =  array(	
						"msg" => "strangerIsDisconnected",
						"p"	=> "2"						
					);
					
					echo json_encode($jsonArray);
					
				}
				
			}else{
				//ben birinci bağlanan kişiyim
				
				$sql = "SELECT * FROM channels WHERE sessionId2 IS NULL AND id=$channelId";
				$resultset = mysql_query($sql);
				
				if(mysql_num_rows($resultset) > 0){
					
					$sql = "UPDATE channels SET lastConnected1=NOW() WHERE id=$channelId";			
					mysql_query($sql);
					$jsonArray =  array(	
							"msg" => "connectionWAITING",
							"me" => $me,
							"channelId" => $channelId						
					);
					
					echo json_encode($jsonArray);
					
				}else{
					
					$sql = "SELECT TIMESTAMPDIFF(SECOND, lastConnected2, NOW()) <=10  FROM channels WHERE id=$channelId";
					$resultset = mysql_query($sql);
					$row = mysql_fetch_row($resultset);
					
					if($row[0] == 1){
						
						// İkinci hala sisteme bağlı ve bende son bağlantı zamanımı güncelliyorum				
						$sql = "UPDATE channels SET lastConnected1=NOW() WHERE id=$channelId";			
						mysql_query($sql);
						$jsonArray =  array(	
								"msg" => "heartBeat"						
						);
						
						echo json_encode($jsonArray);					
						
					}else{
						// İkinci 10 sn'den daha fazla süredir işlem yapmıyor. Yani disconnect
						$jsonArray =  array(	
							"msg" => "strangerIsDisconnected",
							"p"	=> "3"						
						);
						
						echo json_encode($jsonArray);
						
					}
				}
				
			}
			
		}
		
	}else if($action == "online"){

		$sql = "SELECT COUNT(*) FROM channels WHERE status<>2 AND TIMESTAMPDIFF(SECOND, lastConnected1, NOW()) <=10";
		$resultset = mysql_query($sql);
		$row = mysql_fetch_row($resultset);
		
		$jsonArray =  array(	
						"msg" => "online",
						"counter"	=> $row[0]						
					);
					
		echo json_encode($jsonArray);
		
		
	}else if($action == "disconnect"){
		
		$channelId 	= $_GET["channelId"];
		$sql = "UPDATE channels SET status=2 WHERE id=".$channelId;
		
		if(mysql_query($sql)){
				
			$jsonArray =  array(	
					"msg" => "disconnected",
					"channelId" => $channelId,
					"timestamp" => date("Y-m-d H:i:s", time())				
			);
			
			echo json_encode($jsonArray);
			
		}		
		
	}


?>